<template>
  <div class="weibo-card" v-if="postData">
    <div class="weibo-card__header">
      <img :src="'/img'+postData.tx"  class="weibo-card__avatar" @click="toMyHome" />
      <div class="weibo-card__info">
        <span class="weibo-card__nickname">{{ postData.nc }}</span>
        <span class="weibo-card__meta">{{ postData.time }} 来自 微博网页版</span>
        <div class="weibo-card__meta">
          标题# {{ postData.title }}
        </div>
      </div>
      <div class="follow-container" style="margin-left: auto;" v-if="userId && userId !== postData.userId">
        <el-button
            size="small"
            :type="isFollowed ? 'info' : 'primary'"
            @click.stop="handleFollow"
            round
            style="color: orange; --el-button-hover-bg-color:#fcf0de; --el-button-bg-color: #fff; --el-button-color: #ff6b6b; --el-button-hover-border-color: #ee0d64;--el-button-border-color: orange;"
        >
          {{ isFollowed ? '已关注' : '+关注' }}
        </el-button>
      </div>
    </div>

    <div class="weibo-card__content">
      {{ postData.text }}

      <!-- 图片展示 -->
      <div class="weibo-card__image" v-if="postData.url && postData.url.trim()">
        <img  v-for="(imgUrl, index) in postData.url.split(',')"
              :key="index"
              :src="'/img'+imgUrl.trim()"
              class="imgs"
        />
      </div>

      <!-- 视频展示 -->
      <div class="weibo-card__video" v-if="postData.video && postData.video.trim()">
        <video
            v-for="(videoUrl, index) in postData.video.split(',')"
            :key="'video-'+index"
            :src="'/img'+videoUrl.trim()"
            controls
            class="video-player"
        >您的浏览器不支持视频播放</video>
      </div>
    </div>

    <div class="weibo-card__actions">
            <span class="weibo-card__action" @click="showCommentBox = true">
                <el-icon><ChatDotRound /></el-icon>{{ totalCommentCount  }}
            </span>
      <span class="weibo-card__action" @click="handleLike">
                <el-icon class="el-icon" :class="{ 'liked': isLiked }"><Pointer /></el-icon>
                {{ likeCount }}
            </span>
      <span class="weibo-card__action" @click="handleCollect">
                <el-icon :class="{ 'collected': isCollected }"><StarFilled /></el-icon>{{ collectCount }}
            </span>
      <span class="weibo-card__action">
                <el-icon><View /></el-icon>{{ postData.browse || 0 }}
            </span>
    </div>

    <!-- 评论弹窗 -->
    <div class="comment-box" v-if="showCommentBox">
            <textarea
                v-model="commentContent"
                placeholder="说点什么好呢₍˄ ₗ   ̫ ₗ ˄₎◞ ̑̑`"
                class="comment-input"
                rows="3"
            ></textarea>
      <div class="emoji-button-container">
        <button class="emoji-btn" @click.stop="showCommentEmoji = !showCommentEmoji">😊</button>
        <div class="emoji-panel" v-if="showCommentEmoji">
          <span v-for="(emoji, key) in emojis" :key="key" @click="addEmojiToComment(emoji)">{{ emoji }}</span>
        </div>
      </div>
      <div class="comment-actions">
        <button class="cancel-btn" @click="showCommentBox = false">取消</button>
        <button class="send-btn" @click="sendComment">发送</button>
      </div>
    </div>

    <!-- 评论列表-->
    <div class="comment-list">
      <div v-for="comment in commentList" :key="comment.commentId" class="comment-item">
        <div class="comment-header">
          <img :src="'/img' + comment.avatar" class="qwe"/>
          <div class="comment-info">
            <span class="comment-nickname">{{ comment.nickname }}</span>
            <span class="comment-time">{{ comment.commentTime }}</span>
          </div>
          <div class="comment-actions">
            <el-button type="text" @click="showCommentDetail(comment, false)">详情</el-button>
            <el-button type="text" @click="toggleReplyBox(comment)">回复</el-button>
          </div>
        </div>
        <div class="comment-content">
          {{ comment.commentContent }}
        </div>

        <!-- 回复输入框 -->
        <div v-if="comment.showReplyBox" class="reply-input-box" @click.stop>
                    <textarea
                        v-model="comment.replyContent"
                        :placeholder="`回复 @${comment.nickname} 点什么好呢₍˄ ₗ   ̫ ₗ ˄₎◞ ̑̑`"
                        class="reply-textarea"
                        rows="2"
                    ></textarea>
          <div class="emoji-button-container">
            <button class="emoji-btn" @click.stop="comment.showReplyEmoji = !comment.showReplyEmoji">😊</button>
            <div class="emoji-panel" v-if="comment.showReplyEmoji">
              <span v-for="(emoji, key) in emojis" :key="key" @click="addEmojiToReply(comment, emoji)">{{ emoji }}</span>
            </div>
          </div>
          <div class="reply-btns">
            <el-button size="small" @click="sendReply(comment)">发送回复</el-button>
            <el-button size="small" type="text" @click="comment.showReplyBox = false">取消</el-button>
          </div>
        </div>

        <!-- 子评论展示区 -->
        <div class="child-comments-container">
          <div class="child-comments" v-if="comment.children && comment.children.length">
            <el-divider content-position="left">回复 ({{ comment.children.length }})</el-divider>
            <div v-for="child in comment.children" :key="child.commentId" class="child-comment-item">
              <img :src="'/img' + child.avatar" class="child-avatar" />
              <div class="child-comment-content">
                <span class="child-nickname">{{ child.nickname }}</span>
                <span class="child-reply-to"> 回复 @{{ child.repliedNickname }}</span>
                <p class="child-text">{{ child.commentContent }}</p>
                <div class="child-meta">
                  <span class="child-time">{{ child.commentTime }}</span>
                  <el-button
                      size="mini"
                      type="text"
                      @click="showCommentDetail(child, true, comment)"
                  >
                    详情
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 子评论的回复框 -->
          <div v-if="comment.showChildReplyBox" class="reply-input-box" @click.stop>
                        <textarea
                            v-model="comment.childReplyContent"
                            :placeholder="`回复 @${comment.currentChildNickname || '用户'}...`"
                            class="reply-textarea"
                            rows="2"
                        ></textarea>
            <div class="emoji-button-container">
              <button class="emoji-btn" @click.stop="comment.showChildReplyEmoji = !comment.showChildReplyEmoji">😊</button>
              <div class="emoji-panel" v-if="comment.showChildReplyEmoji">
                <span v-for="(emoji, key) in emojis" :key="key" @click="addEmojiToChildReply(comment, emoji)">{{ emoji }}</span>
              </div>
            </div>
            <div class="reply-btns">
              <el-button size="small" @click="sendChildReply(comment)">发送回复</el-button>
              <el-button size="small" type="text" @click="comment.showChildReplyBox = false">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论详情弹窗 -->
    <el-dialog
        :title="isChildComment ? '回复详情' : '评论详情'"
        v-model="dialogVisible"
        width="500px"
    >
      <div v-if="currentComment">
        <p><strong>评论人：</strong>{{ currentComment.nickname }}</p>
        <p><strong>内容：</strong>{{ currentComment.commentContent }}</p>
        <p><strong>时间：</strong>{{ currentComment.commentTime }}</p>
        <p v-if="isChildComment && currentComment.repliedNickname">
          <strong>回复对象：</strong>{{ currentComment.repliedNickname }}
        </p>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button
            type="danger"
            @click="deleteComment(currentComment, isChildComment)"
            :disabled="currentComment.userId !== userId"
        >
          删除
        </el-button>
      </template>
    </el-dialog>
  </div>

  <div v-else>加载中...</div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { ChatDotRound, StarFilled, View, Pointer } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import { ElDialog, ElButton, ElDivider } from 'element-plus';
import { useUserStore } from "@/stores/user";
import { onBeforeRouteUpdate } from 'vue-router'
import router from "../router";

const userStore = useUserStore();
const userId = userStore.id;
const route = useRoute();
const id = route.query.id;

const emojis = ref([
  '😊', '😂', '🤣', '😃', '😄', '😁', '😆', '😅', '🤪', '😉',
  '😍', '😘', '🥰', '😗', '😙', '😚', '😋', '😛', '😜', '😝',
  '🤑', '🤗', '🤭', '🤫', '🤔', '🤐', '🤨', '😐', '😑', '😶',
  '😏', '😒', '🙄', '😬', '🤥', '😌', '😔', '😪', '🤤', '😴',
  '😷', '🤒', '🤕', '🤢', '🤮', '🤧', '🥵', '🥶', '🥴', '😵'
]);

const postData = ref<any>(null);
const commentList = ref<any[]>([]);
const showCommentBox = ref(false);
const commentContent = ref('');
const showCommentEmoji = ref(false);
const dialogVisible = ref(false);
const currentComment = ref<any>({});
const isChildComment = ref(false);
const currentParentComment = ref<any>(null);
const isLiked = ref(false);
const isCollected = ref(false);
const likeCount = ref(0);
const collectCount = ref(0);
const isFollowed = ref(false);
const totalCommentCount = ref(0);

const getFollowStatus = async () => {
  const targetUserId = postData.value?.userId;
  if (!targetUserId || !userId || userId === targetUserId) return;

  try {
    const { data } = await axios.get(`/api/relations/${userId}/${targetUserId}`);
    isFollowed.value = !!data;
  } catch (error) {
    console.error('获取关注状态失败:', error);
    isFollowed.value = false;
  }
};

const handleFollow = async () => {
  const targetUserId = postData.value?.userId;
  if (!targetUserId || !userId || userId === targetUserId) {
    alert("无法关注自己或请先登录");
    return;
  }

  try {
    if (isFollowed.value) {
      const res = await axios.delete(`/api/relation/${userId}/${targetUserId}`);
      if (res.data > 0) {
        isFollowed.value = false;
      }
    } else {
      const followData = {
        fanId: userId,
        userId: targetUserId
      };
      const res = await axios.post('/api/relation', followData);
      if (res.data > 0) {
        isFollowed.value = true;
      }
    }
  } catch (error) {
    console.error('关注操作失败:', error);
    alert('操作失败');
  }
};

onBeforeRouteUpdate((to, from, next) => {
  const id = to.query.id
  if (id) {
    doList(id)
    doListp(id)
  }
  next()
})

onMounted(async () => {
  if (id) {
    await doList(id);
    await doListp(id);
    doListWithAllCount();
    await getLikeStatus();
    await getLikeCount();
    await getCollectStatus();
    await getCollectCount();
    await getFollowStatus();
  } else {
    console.warn("路由参数id不存在，无法加载帖子数据");
  }
});

const doList = async (id) => {
  const { data } = await axios.get(`/api/postAndUser/id/${id}/${userId}`);
  postData.value = data;
  likeCount.value = data.likeCount || 0;
  collectCount.value = data.collectCount || 0;
  await getFollowStatus();
};

const doListp = async (id) => {
  const { data } = await axios.get(`/api/commentp/withReplies/${id}`);
  commentList.value = data.map(comment => ({
    ...comment,
    showReplyBox: false,
    replyContent: '',
    showReplyEmoji: false,
    showChildReplyEmoji: false,
    children: comment.children || [],
    showChildReplyBox: false,
    childReplyContent: '',
    currentChildId: null,
    currentChildNickname: ''
  }));

  totalCommentCount.value = commentList.value.reduce(
      (sum, item) => sum + 1 + (item.children ? item.children.length : 0),
      0
  );
};

const tableData = ref([]);
const doListWithAllCount = async () => {
  const { data } = await axios.get('/api/postAndUser/allCount');
  tableData.value = data;
  console.log(data);
};

const sendComment = async () => {
  if (!commentContent.value.trim()) {
    alert("评论内容不能为空！");
    return;
  }
  const postId = postData.value?.id;
  if (!postId) {
    alert("未找到帖子信息，无法评论！");
    return;
  }
  const comment = {
    postId: Number(postId),
    userId: Number(userId),
    text: commentContent.value,
    useredId: 0,
    url: null,
    parentId: null
  };
  if (comment.userId === 0) {
    alert("请先登录！");
    return;
  } else {
    await axios.post("/api/comment", comment);
    postData.value.commentCount = (postData.value.commentCount || 0) + 1;
    commentContent.value = "";
    showCommentBox.value = false;
    showCommentEmoji.value = false;
    doListp(id);
  }
};

const addEmojiToComment = (emoji: string) => {
  commentContent.value += emoji;
};

const addEmojiToReply = (comment: any, emoji: string) => {
  comment.replyContent += emoji;
};

const addEmojiToChildReply = (comment: any, emoji: string) => {
  comment.childReplyContent += emoji;
};

const showCommentDetail = (comment: any, isChild: boolean, parentComment?: any) => {
  currentComment.value = comment;
  isChildComment.value = isChild;
  currentParentComment.value = parentComment;
  dialogVisible.value = true;
};

const deleteComment = async (comment: any, isChild: boolean) => {
  if (comment === null || comment === undefined) {
    alert('未选中评论，无法删除');
    return;
  }
  const commentId = comment.commentId;
  if (!commentId) {
    alert('未找到评论ID，无法删除');
    return;
  }
  const commentUserId = comment.userId;
  if (Number(userId) !== Number(commentUserId)) {
    alert('您不能删除别人的评论哦o(>﹏<)o');
    return;
  }

  if (!confirm('确定要删除这条评论吗？')) {
    return;
  }

  await axios.delete(`/api/comment/${commentId}`);

  if (isChild && currentParentComment.value) {
    currentParentComment.value.children = currentParentComment.value.children.filter(
        (child: any) => child.commentId !== commentId
    );
  }

  doListp(id);
  dialogVisible.value = false;
};

const handleLike = async () => {
  const postId = postData.value?.id;
  if (!postId || !userId) {
    alert("请先登录或帖子不存在");
    return;
  }
  if (isLiked.value) {
    const res = await axios.delete(`/api/like/${postId}/${userId}`);
    if (res.data > 0) {
      isLiked.value = false;
      likeCount.value--;
    }
  } else {
    const likeData = {
      postId: postId,
      userId: userId,
      time: new Date().toISOString()
          .replace('T', ' ')
          .slice(0, 19)
    };
    const res = await axios.post('/api/like', likeData);
    if (res.data > 0) {
      isLiked.value = true;
      likeCount.value++;
    }
  }
};

const getLikeStatus = async () => {
  const postId = postData.value?.id;
  if (postId && userId) {
    const { data: likeData } = await axios.get(`/api/like/${postId}/${userId}`);
    isLiked.value = !!likeData;
  }
};

const getLikeCount = async () => {
  const postId = postData.value?.id;
  if (postId) {
    const { data: count } = await axios.get(`/api/likes/${postId}`);
    likeCount.value = count;
  }
};

const handleCollect = async () => {
  const postId = postData.value?.id;
  if (!postId || !userId) { alert("请先登录或帖子不存在"); return; }
  if (isCollected.value) {
    const { data: collectId } = await axios.get(`/api/collect/user/${userId}/post/${postId}`);
    if (!collectId) { alert("未找到收藏记录"); return; }
    const res = await axios.delete(`/api/collect/${collectId}`);
    if (res.data > 0) {
      isCollected.value = false;
      collectCount.value--;
    }
  } else {
    const collectData = {
      userId: userId,
      postId: postId,
      time: new Date().toISOString().replace('T', ' ').slice(0, 19)
    };
    const res = await axios.post('/api/collect', collectData);
    if (res.data > 0) {
      isCollected.value = true;
      collectCount.value++;
    }
  }
};

const getCollectStatus = async () => {
  const postId = postData.value?.id;
  if (postId && userId) {
    const { data: status } = await axios.get(`/api/collect/status/user/${userId}/post/${postId}`);
    isCollected.value = status;
  }
};

const getCollectCount = async () => {
  const postId = postData.value?.id;
  if (postId) {
    const { data: count } = await axios.get(`/api/collects/${postId}`);
    collectCount.value = count;
  }
};

const toggleReplyBox = (comment) => {
  commentList.value.forEach(item => {
    if (item.commentId !== comment.commentId) {
      item.showReplyBox = false;
      item.showChildReplyBox = false;
      item.showReplyEmoji = false;
      item.showChildReplyEmoji = false;
    }
  });
  comment.showReplyBox = !comment.showReplyBox;
  if (comment.showReplyBox) {
    comment.showChildReplyBox = false;
  }
};

const sendReply = async (comment) => {
  if (!comment.replyContent.trim()) {
    alert("回复内容不能为空！");
    return;
  }
  const postId = postData.value?.id;
  if (!postId) {
    alert("未找到帖子信息，无法回复！");
    return;
  }
  const replyData = {
    postId: Number(postId),
    userId: Number(userId),
    text: comment.replyContent,
    useredId: 0,
    url: null,
    parentId: comment.commentId
  };
  if (replyData.userId === 0) {
    alert("请先登录！");
    return;
  }
  await axios.post("/api/comment", replyData);
  comment.showReplyBox = false;
  comment.showReplyEmoji = false;
  comment.replyContent = "";
  doListp(id);
};

const sendChildReply = async (comment) => {
  if (!comment.childReplyContent.trim()) {
    alert("回复内容不能为空！");
    return;
  }
  const postId = postData.value?.id;
  if (!postId || !comment.currentChildId) {
    alert("回复失败，请重试！");
    return;
  }
  const replyData = {
    postId: Number(postId),
    userId: Number(userId),
    text: comment.childReplyContent,
    useredId: 0,
    url: null,
    parentId: comment.currentChildId
  };
  if (replyData.userId === 0) {
    alert("请先登录！");
    return;
  }
  await axios.post("/api/comment", replyData);
  comment.showChildReplyBox = false;
  comment.showChildReplyEmoji = false;
  comment.childReplyContent = "";
  comment.currentChildId = null;
  comment.currentChildNickname = "";
  doListp(id);
};

const toMyHome = () => {
  router.push({
    path: '/hoet',
    query: {
      id: postData.value.userId
    }
  });
};
</script>

<style scoped>
.qwe{
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}
.weibo-card {
  display: flex;
  height: auto;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.weibo-card__header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.weibo-card__avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 8px;
}
.weibo-card__info {
  display: flex;
  flex-direction: column;
}
.weibo-card__nickname {
  font-weight: bold;
  color: #333;
}
.weibo-card__meta {
  font-size: 12px;
  color: #999;
}
.weibo-card__content {
  margin: 8px 0;
  text-align: center;
  color: #333;
  line-height: 1.6;
}
.weibo-card__image {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}
.weibo-card__image img {
  max-width: 280px;
  width: auto;
  max-height: 280px;
  height: auto;
  border-radius: 4px;
}
.weibo-card__video {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}
.video-player {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
  background-color: #000;
  outline: none;
}
.weibo-card__actions {
  display: flex;
  gap: 24px;
  color: #666;
  margin-top: 8px;
  cursor: pointer;
  justify-content: center;
}
.weibo-card__action {
  display: flex;
  align-items: center;
  gap: 4px;
  transition: color 0.2s;
}
.weibo-card__action:hover {
  color: #409eff;
}

::v-deep .weibo-card__action .liked {
  color: #ff4d4f;
}
::v-deep .weibo-card__action .collected {
  color: #faad14;
}

.comment-box {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}
.comment-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  font-size: 14px;
}
.comment-input:focus {
  outline: none;
  border-color: #409eff;
}
.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 8px;
}
.cancel-btn, .send-btn {
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}
.cancel-btn {
  border: 1px solid #ddd;
  background-color: #fff;
  color: #666;
}
.cancel-btn:hover {
  border-color: #ccc;
  background-color: #f5f5f5;
}
.send-btn {
  border: none;
  background-color: #409eff;
  color: #fff;
}
.send-btn:hover {
  background-color: #66b1ff;
}
.imgs{
  width: 133px;
  height: 133px;
  margin: 0 2px;
}

.emoji-button-container {
  position: relative;
  margin: 8px 0;
}

.emoji-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.emoji-btn:hover {
  background-color: #f0f0f0;
}

.emoji-panel {
  position: absolute;
  z-index: 100;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 300px;
  max-height: 200px;
  overflow-y: auto;
}

.emoji-panel span {
  font-size: 20px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.emoji-panel span:hover {
  background-color: #f0f0f0;
}

.comment-list {
  margin-top: 16px;
  border-top: 1px solid #eee;
  padding-top: 16px;
}
.comment-item {
  padding: 12px;
  border-radius: 6px;
  background-color: #f9f9f9;
  margin-bottom: 12px;
}
.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
.comment-info {
  margin-left: 12px;
  flex: 1;
}
.comment-nickname {
  font-weight: 500;
  margin-right: 8px;
}
.comment-time {
  font-size: 12px;
  color: #999;
}
.comment-content {
  margin-bottom: 12px;
  padding-left: 72px;
}

.reply-input-box {
  margin: 8px 0;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}
.reply-textarea {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
  resize: none;
  margin-bottom: 10px;
}
.reply-textarea:focus {
  outline: none;
  border-color: #409eff;
}
.reply-btns {
  text-align: right;
}

.child-comments-container {
  margin-top: 12px;
  padding-left: 72px;
}
.child-comments {
  margin-bottom: 12px;
}
.child-comment-item {
  display: flex;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px dashed #f0f0f0;
}
.child-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
}
.child-comment-content {
  flex: 1;
}
.child-nickname {
  font-weight: 500;
  margin-right: 4px;
}
.child-reply-to {
  color: #909399;
  font-size: 12px;
}
.child-text {
  margin: 4px 0;
  font-size: 14px;
}
.child-meta {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #909399;
  gap: 12px;
}
.child-time {
  margin-right: 8px;
}

::v-deep .el-button--danger.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .video-player {
    max-height: 300px;
  }
}

@media (max-width: 480px) {
  .video-player {
    max-height: 200px;
  }
}
</style>